package com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.service.impl;

import com.css.fxfzxczh.constants.XczhConstants;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.entity.HouMonData;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.repository.HouMonDataRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.vo.TotalFloorageVO;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.entity.SamPoiData;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.repository.SamPoiDataRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.service.SamPoiDataService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.HouDamSta;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.SamPoiHouSur;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.service.SamPoiHouSurService;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.entity.*;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.repository.HouseEconomicLossAssessRepository;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.service.HouseEconomicLossAssessService;
import com.css.fxfzxczh.modules.eqDisasterLossAssess.houseEconomicLossAssess.vo.CalculationResultVo;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.entity.SurTaskManage;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.repository.SurTaskManageRepository;
import com.css.fxfzxczh.modules.fieldWorkManage.surTaskManage.service.SurTaskManageService;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.entity.HouseCategoryArea;
import com.css.fxfzxczh.modules.lossAssessment.houseCategoryArea.repository.HouseCategoryAreaRepository;
import com.css.fxfzxczh.modules.lossAssessment.resetPrice.entity.ResetPrice;
import com.css.fxfzxczh.modules.lossAssessment.resetPrice.repository.ResetPriceRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.repository.EarEveManageRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.houseStructureManagement.service.HouseStructureManagementService;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.util.UUIDGenerator;
import com.css.fxfzxczh.web.PlatformSessionContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HouseEconomicLossAssessServiceImpl implements HouseEconomicLossAssessService {

    @Autowired
    SurTaskManageService surTaskManageService;
    @Autowired
    SamPoiDataService samPoiDataService;
    @Autowired
    SamPoiHouSurService samPoiHouSurService;
    @Autowired
    HouseEconomicLossAssessRepository houseEconomicLossAssessRepository;
    @Autowired
    ResetPriceRepository resetPriceRepository;
    @Autowired
    HouseCategoryAreaRepository houseCategoryAreaRepository;
    @Autowired
    HouseStructureManagementService houseStructureManagementService;
    @Autowired
    HouseEconomicLossAssessService houseEconomicLossAssessService;
    @Autowired
    EarEveManageRepository earEveManageRepository;
    @Autowired
    HouMonDataRepository houMonDataRepository;
    @Autowired
    SamPoiDataRepository samPoiDataRepository;

    @Autowired
    SurTaskManageRepository surTaskManageRepository;

    @Override
    public List<SurTaskManage> getEvaluationSubArea(String xsemId) {
       /* List<SurTaskManage> evaluationSubArea = surTaskManageService.getTaskListByXsemId(xsemId);
        return evaluationSubArea;*/
//获取当前地震事件
        EarEveManage earEveManage = earEveManageRepository.findById(xsemId);
        //String xsemCode = earEveManage.getEventCode();
        List<SurTaskManage> list = new ArrayList<>();
        List<SurTaskManage> surList = surTaskManageService.getTaskByTypeAndXsemId(xsemId);
        if (surList.size() > 0) {
            for (SurTaskManage surTaskManage : surList) {
                HouseCategoryArea typeTotalArea = houseCategoryAreaRepository.getTypeTotalAreaByXstmId(surTaskManage.getXstmId());
                if(PlatformObjectUtils.isEmpty(typeTotalArea)){
                    continue;
                }
                if (PlatformObjectUtils.isNotEmpty(surTaskManage)) {
                    List<SamPoiData> samList = samPoiDataService.getSamPoiListByXstmId(surTaskManage.getXstmId());
                    //todo 暂时这样写，后续调查任务逻辑完善，需删除
//                            List<SamPoiData> supSamPoiList=samPoiDataRepository.getSamListByType("0");
//                            for(SamPoiData item:supSamPoiList){
//                                Boolean boo=samPoiDataRepository.judPointPosition(surTaskManage.getXstmId(),item.getLongitude(),item.getLatitude());
//                                if(boo){
//                                    samList.add(item);
//                                }
//                            }
                    if (samList.size() > 0) {
                        for (SamPoiData samPoiData : samList) {
                            SamPoiHouSur samPoiHouSur = samPoiHouSurService.getTaskListByXspdId(samPoiData.getId());
                            if (PlatformObjectUtils.isNotEmpty(samPoiHouSur)) {
                                list.add(surTaskManage);
                            }
                        }
                    }
                }
            }
        }
        //List<String>  personnelIds = personnelIdList.stream().distinct().collect(Collectors.toList());

        return list.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getEvaluationSubAreaList(String xsemId) {
        List<SurTaskManage> surList = surTaskManageService.getTaskByTypeAndXsemId(xsemId);
        Map<String, Object> map = new HashMap<>();
        List<SurTaskManage> list = new ArrayList<>();
        StringBuilder message=new StringBuilder("");
        if(!CollectionUtils.isEmpty(surList)){
            for (SurTaskManage surTaskManage : surList) {
                if (PlatformObjectUtils.isNotEmpty(surTaskManage)) {
                    List<SamPoiData> samList = samPoiDataService.getSamPoiListByXstmId(surTaskManage.getXstmId());
                    if (samList.size() > 0) {
                        for (SamPoiData samPoiData : samList) {
                            SamPoiHouSur samPoiHouSur = samPoiHouSurService.getTaskListByXspdId(samPoiData.getId());
                            if (PlatformObjectUtils.isNotEmpty(samPoiHouSur)) {
                                list.add(surTaskManage);
                            }
                        }
                    }else{
                        message.append(surTaskManage.getEvaluationSubareaName()+" 没有现场调查数据，请先进行现场调查再划定评估子区,<br/>");
                    }
                }
            }
        }else {
            map.put("list", list);
            map.put("message", message.append("该地震事件没有划定评估子区,请先进行现场调查再划定评估子区"));
            return map;
        }
        map.put("list", list.stream().distinct().collect(Collectors.toList()));
        map.put("message", !StringUtils.isBlank(message) ? message.substring(0, message.length() - 6) : message);
        return map;
    }


    @Override
    public String getMessage(String xsemId) {
        String message = "";
        String str = "";
        //获取当前地震事件中所有的评估子区
        List<SurTaskManage> evaluationSubArea = surTaskManageService.getTaskListByXsemId(xsemId);
        List<String> name = new ArrayList<>();
        for(SurTaskManage surTaskManage : evaluationSubArea){
            name.add(surTaskManage.getEvaluationSubareaName());
        }
        //获取已经计算的所有评估子区
        List<HouseFailureRatioEntity> list = houseEconomicLossAssessRepository.getHouseFailureRatioByXsemId(xsemId);
        //获取b中不包含a的元素
        if(!PlatformObjectUtils.isEmpty(list)){
            for(HouseFailureRatioEntity houseFailureRatioEntity : list){
                if(!(name.contains(houseFailureRatioEntity.getEvaluationSubareaName()))){
                    str += houseFailureRatioEntity.getEvaluationSubareaName() +"、";
                }
            }
        }else{
            for(String evaluationSubareaName : name){
                str += evaluationSubareaName +"、";
            }
        }
        if(!PlatformObjectUtils.isEmpty(str)){
            str = str.substring(0,str.length()-1);
            message = "还有"+str+"评估子区没有破坏比计算值,无法进行直接经济损失计算";
        }else{
            message = "所有评估子区破坏比已全部计算完成";
        }
        return message;
    }

    @Override
    public Map<String, Object> page(String xsemId, String xstmId, int curPage, int pageSize) {
        List<String> types = houseStructureManagementService.getPreStrType("预置");
        List<HouseFailureRatioEntity> list = new ArrayList<>();
        if (PlatformObjectUtils.isEmpty(xstmId)) {
            //获取当前地震事件下所有数据齐全的评估子区
            List<SurTaskManage> evaluationSubArea = getEvaluationSubArea(xsemId);
            for (SurTaskManage surTaskManage : evaluationSubArea) {
                //根据评估子区id获取已计算的数据
                List<HouseFailureRatioEntity> houseFailureRatioList = houseEconomicLossAssessRepository.getHouseFailureRatioByXstmId(surTaskManage.getXstmId());
                //为空则添加空数据
                if (PlatformObjectUtils.isEmpty(houseFailureRatioList)) {
                    for (String type : types) {
                        HouseFailureRatioEntity houseFailureRatioEntity = new HouseFailureRatioEntity();
                        houseFailureRatioEntity.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                        houseFailureRatioEntity.setStructureType(type);
                        houseFailureRatioList.add(houseFailureRatioEntity);
                    }
                }
                list.addAll(houseFailureRatioList);
            }
        } else {
            SurTaskManage surTaskManage = surTaskManageService.findById(xstmId);
            //根据评估子区id获取已计算的数据
            List<HouseFailureRatioEntity> houseFailureRatioList = houseEconomicLossAssessRepository.getHouseFailureRatioByXstmId(xstmId);
            //为空则添加空数据
            if (PlatformObjectUtils.isEmpty(houseFailureRatioList)) {
                for (String type : types) {
                    HouseFailureRatioEntity houseFailureRatioEntity = new HouseFailureRatioEntity();
                    houseFailureRatioEntity.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                    houseFailureRatioEntity.setStructureType(type);
                    houseFailureRatioList.add(houseFailureRatioEntity);
                }
            }
            list.addAll(houseFailureRatioList);
        }

        //分页查询
        List<HouseFailureRatioEntity> houseFailureRatioEntities = startPage(list, curPage, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
        map.put("rows", houseFailureRatioEntities);
        return map;
    }

    @Override
    public void getAdministrationAreaHousesDirectEconomicLosses(String xsemId) {
        List<CalculationResultVo> list = new ArrayList<>();
        //删除上一次的计算结果
        houseEconomicLossAssessRepository.delAdministrationAreaHousesDirectEconomicLosses(xsemId);
        //获取当前地震事件
        EarEveManage earEveManage = earEveManageRepository.findById(xsemId);
        String xsemCode = earEveManage.getEventCode();
        List<String> xstmIds = houseCategoryAreaRepository.getxstmIdByXsemId(xsemId);
        for (String xstmId : xstmIds) {


            //获取预置的十大结构类型
            List<String> types = houseStructureManagementService.getPreStrType("预置");
            //Sh--根据评估子区,省市县,用途种类查询所有结构类型的建筑面积
            List<HouseCategoryArea> typeTotalArea = houseCategoryAreaRepository.getSumArea(xsemId, xstmId);
            //Rh——该评估子区同类房屋某种破坏等级的破坏比；
            List<HouseFailureRatioEntity> houseFailureRatioList = houseEconomicLossAssessRepository.getHouseFailureRatioByXstmId(xstmId);


            //Dh——该评估子区同类房屋某种破坏等级的损失比；
            HouseLossRatioEntity houseLossRatio = houseEconomicLossAssessRepository.getHouseLossRatio(xsemId);
            //Ph——该评估子区同类房屋重置单价，单位为元每平方米。
            List<ResetPrice> resetPriceList = resetPriceRepository.getResetPriceByXsemId(xsemId);
            for (HouseCategoryArea area : typeTotalArea) {
                //房屋用途十大结构损失之和
                BigDecimal allStructureTotalLoss = BigDecimal.ZERO;
                for (String type : types) {
                    //Sh 总面积
                    Double totalArea = 0.0;
                    //Rh 破坏比
                    BigDecimal intactRatio = BigDecimal.ZERO; //基本完好
                    BigDecimal minorRatio = BigDecimal.ZERO; //轻微破坏
                    BigDecimal moderateRatio = BigDecimal.ZERO;//中等破坏
                    BigDecimal seriousRatio = BigDecimal.ZERO; //严重破坏
                    BigDecimal destroyRatio = BigDecimal.ZERO; //毁坏
                    //Dh 损失比
                    BigDecimal intact = BigDecimal.ZERO; //基本完好
                    BigDecimal minor = BigDecimal.ZERO; //轻微破坏
                    BigDecimal moderate = BigDecimal.ZERO;//中等破坏
                    BigDecimal serious = BigDecimal.ZERO; //严重破坏
                    BigDecimal destroy = BigDecimal.ZERO; //毁坏
                    //ph 单价
                    BigDecimal price = BigDecimal.ZERO;
                    if (XczhConstants.ONE_TYPE.equals(type)) {
                        totalArea = area.getV1Area().doubleValue();
                    } else if (XczhConstants.TWO_TYPE.equals(type)) {
                        totalArea = area.getV2Area().doubleValue();
                    } else if (XczhConstants.THREE_ONE_TYPE.equals(type)) {
                        totalArea = area.getV3Area().doubleValue();
                    } else if (XczhConstants.THREE_TWO_TYPE.equals(type)) {
                        totalArea = area.getV4Area().doubleValue();
                    } else if (XczhConstants.FOUR_TYPE.equals(type)) {
                        totalArea = area.getV5Area().doubleValue();
                    } else if (XczhConstants.FIVE_ONE_TYPE.equals(type)) {
                        totalArea = area.getV6Area().doubleValue();
                    } else if (XczhConstants.FIVE_TWO_TYPE.equals(type)) {
                        totalArea = area.getV7Area().doubleValue();
                    } else if (XczhConstants.FIVE_THREE_TYPE.equals(type)) {
                        totalArea = area.getV8Area().doubleValue();
                    } else if (XczhConstants.SIX_TYPE.equals(type)) {
                        totalArea = area.getV9Area().doubleValue();
                    } else if (XczhConstants.SEVEN_TYPE.equals(type)) {
                        totalArea = area.getV10Area().doubleValue();
                    }

                    if (XczhConstants.TWO_TYPE.equals(type) || XczhConstants.THREE_ONE_TYPE.equals(type) ||
                            XczhConstants.THREE_TWO_TYPE.equals(type) || XczhConstants.SEVEN_TYPE.equals(type)) {//钢筋混凝土、砌体房屋     Dh
                        intact = percentageConvert (new BigDecimal(houseLossRatio.getIntact1()));
                        minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor1()));
                        moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate1()));
                        serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious1()));
                        destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy1()));
                    } else if (XczhConstants.SIX_TYPE.equals(type)) {//工业厂房
                        intact = percentageConvert (new BigDecimal(houseLossRatio.getIntact2()));
                        minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor2()));
                        moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate2()));
                        serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious2()));
                        destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy2()));
                    } else if (XczhConstants.ONE_TYPE.equals(type)) {//钢机构
                        intact = percentageConvert (new BigDecimal(houseLossRatio.getIntact4()));
                        minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor4()));
                        moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate4()));
                        serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious4()));
                        destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy4()));
                    } else if (XczhConstants.FOUR_TYPE.equals(type) || XczhConstants.FIVE_ONE_TYPE.equals(type) ||
                            XczhConstants.FIVE_TWO_TYPE.equals(type) || XczhConstants.FIVE_THREE_TYPE.equals(type)) {//城镇平房、农村房屋
                        intact = percentageConvert (new BigDecimal(houseLossRatio.getIntact3()));
                        minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor3()));
                        moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate3()));
                        serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious3()));
                        destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy3()));
                    }

                    for (ResetPrice resetPrice : resetPriceList) {
                        if (type.equals(resetPrice.getStructureType())) {
                            price = new BigDecimal(resetPrice.getResetPrice());
                        }
                    }
                    for (HouseFailureRatioEntity houseFailureRatio : houseFailureRatioList) {
                        if (type.equals(houseFailureRatio.getStructureType())) {
                            intactRatio = new BigDecimal(houseFailureRatio.getIntactRatio());
                            minorRatio = new BigDecimal(houseFailureRatio.getMinorRatio());
                            moderateRatio = new BigDecimal(houseFailureRatio.getModerateRatio());
                            seriousRatio = new BigDecimal(houseFailureRatio.getSeriousRatio());
                            destroyRatio = new BigDecimal(houseFailureRatio.getDestroyRatio());
                        }
                    }
                    //计算每一种破坏程度的值
                    BigDecimal intactValue = calculation(BigDecimal.valueOf(totalArea), intactRatio, intact, price);
                    BigDecimal minorValue = calculation(BigDecimal.valueOf(totalArea), minorRatio, minor, price);
                    BigDecimal moderateValue = calculation(BigDecimal.valueOf(totalArea), moderateRatio, moderate, price);
                    BigDecimal seriousValue = calculation(BigDecimal.valueOf(totalArea), seriousRatio, serious, price);
                    BigDecimal destroyValue = calculation(BigDecimal.valueOf(totalArea), destroyRatio, destroy, price);
                    //房屋损失(元)
                    BigDecimal structureTotalLoss = intactValue.add(minorValue).add(moderateValue).add(seriousValue).add(destroyValue);
                    System.out.println(structureTotalLoss);
                    allStructureTotalLoss = allStructureTotalLoss.add(structureTotalLoss);
                }
                CalculationResultVo calculationResultVo = new CalculationResultVo();
                calculationResultVo.setXstmId(xstmId);
                calculationResultVo.setProvince(area.getProvince());
                calculationResultVo.setCity(area.getCity());
                calculationResultVo.setCounty(area.getCounty());
                calculationResultVo.setHousePurposeCode(area.getHousePurposeCode());
                calculationResultVo.setAllStructureTotal(allStructureTotalLoss);
                list.add(calculationResultVo);
            }
        }


        //处理计算的结果集,根据省市县分组
        Map<String, List<CalculationResultVo>> countyGroup = new HashMap<>();
        for(CalculationResultVo calculationResultVo : list){
            String province = calculationResultVo.getProvince();
            String city = calculationResultVo.getCity();
            String county = calculationResultVo.getCounty();
            String key = province+"_"+city+"_"+county;
            if (!countyGroup.containsKey(key)) {
                countyGroup.put(key, new ArrayList<>());
            }
            countyGroup.get(key).add(calculationResultVo);
        }
        List<AdministrationAreaHousesDirectEconomicLosses> list1 = new ArrayList<>();
        for(String key : countyGroup.keySet()) {
            BigDecimal housePurposeValue1 = BigDecimal.valueOf(0.0);
            BigDecimal housePurposeValue2 = BigDecimal.valueOf(0.0);
            BigDecimal housePurposeValue3 = BigDecimal.valueOf(0.0);
            BigDecimal housePurposeValue4 = BigDecimal.valueOf(0.0);
            BigDecimal housePurposeValue5 = BigDecimal.valueOf(0.0);
            BigDecimal housePurposeValue6 = BigDecimal.valueOf(0.0);
            BigDecimal housePurposeValue7 = BigDecimal.valueOf(0.0);
            BigDecimal housePurposeValue8 = BigDecimal.valueOf(0.0);
            BigDecimal totalLoss = BigDecimal.valueOf(0.0);
            List<CalculationResultVo> CalculationResultVos = countyGroup.get(key);
            String countyTotal = "";
            for (CalculationResultVo calculationResultVo : CalculationResultVos) {
                String housePurposeCode = calculationResultVo.getHousePurposeCode();
                if(XczhConstants.VILLAGE_HOUSE.equals(housePurposeCode)){
                    housePurposeValue1=housePurposeValue1.add(calculationResultVo.getAllStructureTotal());
                }else if(XczhConstants.VILLAGE_PUBLIC.equals(housePurposeCode)){
                    housePurposeValue2=housePurposeValue2.add(calculationResultVo.getAllStructureTotal());
                }else if(XczhConstants.CITY_HOUSE.equals(housePurposeCode)){
                    housePurposeValue3=housePurposeValue3.add(calculationResultVo.getAllStructureTotal());
                }else if(XczhConstants.CITY_PUBLIC.equals(housePurposeCode)){
                    housePurposeValue4=housePurposeValue4.add(calculationResultVo.getAllStructureTotal());
                }else if(XczhConstants.GOVERNMENT_WORK.equals(housePurposeCode)){
                    housePurposeValue5=housePurposeValue5.add(calculationResultVo.getAllStructureTotal());
                }else if(XczhConstants.EDUCATION_SYSTEM.equals(housePurposeCode)){
                    housePurposeValue6=housePurposeValue6.add(calculationResultVo.getAllStructureTotal());
                }else if(XczhConstants.HEALTH_SYSTEM.equals(housePurposeCode)){
                    housePurposeValue7=housePurposeValue7.add(calculationResultVo.getAllStructureTotal());
                }else if(XczhConstants.OTHER.equals(housePurposeCode)){
                    housePurposeValue8=housePurposeValue8.add(calculationResultVo.getAllStructureTotal());
                }
            }

            //totalLoss = housePurposeValue1+housePurposeValue2+housePurposeValue3+housePurposeValue4+housePurposeValue5+housePurposeValue6+housePurposeValue7;
            totalLoss = housePurposeValue1.add(housePurposeValue2).add(housePurposeValue3).add(housePurposeValue4).add(housePurposeValue5).add(housePurposeValue6).add(housePurposeValue7).add(housePurposeValue8);
            AdministrationAreaHousesDirectEconomicLosses entity = new AdministrationAreaHousesDirectEconomicLosses();
            entity.setId(UUIDGenerator.getUUID());
            entity.setXsemId(xsemId);
            String province = key.split("_")[0];
            String city = key.split("_")[1];
            String county = key.split("_")[2];
            entity.setProvince(province);
            entity.setCity(city);
            entity.setCounty(county);
            entity.setRuralHouse(housePurposeValue1.divide(new BigDecimal("10000")));
            entity.setRuralShared(housePurposeValue2.divide(new BigDecimal("10000")));
            entity.setCityHouse(housePurposeValue3.divide(new BigDecimal("10000")));
            entity.setCityShared(housePurposeValue4.divide(new BigDecimal("10000")));
            entity.setGovernmentOffice(housePurposeValue5.divide(new BigDecimal("10000")));
            entity.setEducationSystem(housePurposeValue6.divide(new BigDecimal("10000")));
            entity.setHealthSystem(housePurposeValue7.divide(new BigDecimal("10000")));
            entity.setOtherUsage(housePurposeValue8.divide(new BigDecimal("10000")));
            entity.setTotalLoss(totalLoss.divide(new BigDecimal("10000")));
            entity.setCreateTime(new Date());
            entity.setCreateUser(PlatformSessionContext.getUserID());
            entity.setDelFlag(YNEnum.N.toString());
            list1.add(entity);
            //保存
            houseEconomicLossAssessRepository.saveAdministrationAreaHousesDirectEconomicLosses(entity);
        }
    }

    @Override
    public List<AdministrationAreaHousesDirectEconomicLosses> getAdministrationData(String xsemId) {
        return houseEconomicLossAssessRepository.getAdministrationData(xsemId);
    }

    @Override
    public Map<String, Object> directPage(String xsemId, String xstmId, int curPage, int pageSize) {
        List<String> types = houseStructureManagementService.getPreStrType("预置");
        List<HousesDirectEconomicLosses> list = new ArrayList<>();
        if (PlatformObjectUtils.isEmpty(xstmId)) {
            //获取当前地震事件下所有数据齐全的评估子区
            List<SurTaskManage> evaluationSubArea = getEvaluationSubArea(xsemId);
            for (SurTaskManage surTaskManage : evaluationSubArea) {
                //根据评估子区id获取已计算的数据
                List<HousesDirectEconomicLosses> HousesDirectEconomicLossesList = houseEconomicLossAssessRepository.getHousesDirectEconomicLossesByXstmId(surTaskManage.getXstmId());
                //为空则添加空数据
                if (PlatformObjectUtils.isEmpty(HousesDirectEconomicLossesList)) {
                    for (String type : types) {
                        HousesDirectEconomicLosses housesDirectEconomicLosses = new HousesDirectEconomicLosses();
                        housesDirectEconomicLosses.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                        housesDirectEconomicLosses.setStructureType(type);
                        HousesDirectEconomicLossesList.add(housesDirectEconomicLosses);
                    }
                }
                list.addAll(HousesDirectEconomicLossesList);
            }
        } else {
            SurTaskManage surTaskManage = surTaskManageService.findById(xstmId);
            //根据评估子区id获取已计算的数据
            List<HousesDirectEconomicLosses> HousesDirectEconomicLossesList = houseEconomicLossAssessRepository.getHousesDirectEconomicLossesByXstmId(surTaskManage.getXstmId());
            //为空则添加空数据
            if (PlatformObjectUtils.isEmpty(HousesDirectEconomicLossesList)) {
                for (String type : types) {
                    HousesDirectEconomicLosses housesDirectEconomicLosses = new HousesDirectEconomicLosses();
                    housesDirectEconomicLosses.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                    housesDirectEconomicLosses.setStructureType(type);
                    HousesDirectEconomicLossesList.add(housesDirectEconomicLosses);
                }
            }
            list.addAll(HousesDirectEconomicLossesList);
        }

        //分页查询
        List<HousesDirectEconomicLosses> houseFailureRatioEntities = startPage(curPage, pageSize,list);
        Map<String, Object> map = new HashMap<>();
        map.put("total", PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
        map.put("rows", houseFailureRatioEntities);
        return map;
    }

    @Override
    public List<HouseFailureRatioEntity> getFailureRatioByXsemId(String xsemId) {
        return houseEconomicLossAssessRepository.getHouseFailureRatioByXsemId(xsemId);
    }

    private  List<HouseFailureRatioEntity> startPage(List<HouseFailureRatioEntity> list, Integer pageNum, Integer pageSize) {
        if (list.size() == 0) {
            return null;
        }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List<HouseFailureRatioEntity> pageList = list.subList(fromIndex, toIndex);
        return pageList;
    }

    private  List<HousesDirectEconomicLosses> startPage( Integer pageNum, Integer pageSize,List<HousesDirectEconomicLosses> list) {
        if (list.size() == 0) {
            return null;
        }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List<HousesDirectEconomicLosses> pageList = list.subList(fromIndex, toIndex);
        return pageList;
    }


    @Override
    public void getFailureRatio(String xsemId) {
        List<HouDamSta> list = new ArrayList<>();
        //获取当前地震事件
        EarEveManage earEveManage = earEveManageRepository.findById(xsemId);
        String xsemCode = earEveManage.getEventCode();
        //获取当前地震事件下数据齐全的所有的评估子区
        //删除评估子区中之前计算的数据
        houseEconomicLossAssessRepository.deleteHouseFailureRatio(xsemId);
        List<SurTaskManage> surTaskManageList = houseEconomicLossAssessService.getEvaluationSubArea(xsemId);
        //todo 暂时这样写，后续调查任务逻辑完善，需删除
//        List<SamPoiData> supSamPoiList=samPoiDataRepository.getSamListByType("0");
        //补充抽样点id集合
        List<String> supSamPoiIdList=new ArrayList<>();

        for (SurTaskManage surTaskManage : surTaskManageList) {
            String xstmId = surTaskManage.getXstmId();
            String evaluationSubareaName = surTaskManage.getEvaluationSubareaName();
            //通过评估子区id获取到抽样点
            List<SamPoiData> samPoiList = samPoiDataService.getSamPoiListByXstmId(xstmId);


//            for(SamPoiData item:supSamPoiList){
//                Boolean boo=samPoiDataRepository.judPointPosition(surTaskManage.getXstmId(),item.getLongitude(),item.getLatitude());
//                if(boo){
//                    supSamPoiIdList.add(item.getId());
//                    samPoiList.add(item);
//                }
//            }




            if (!PlatformObjectUtils.isEmpty(samPoiList)) {
                for (SamPoiData samPoiData : samPoiList) {
                    //通过抽样点获取到房屋抽样点
                    SamPoiHouSur samPoiHouSur = samPoiHouSurService.getTaskListByXspdId(samPoiData.getId());
                    //通过房屋抽样点id获取到不同结构不同破坏状态下的面积和百分比
                    if (!PlatformObjectUtils.isEmpty(samPoiHouSur) && !PlatformObjectUtils.isEmpty(samPoiHouSur.getId())) {
                        List<HouDamSta> staResult = samPoiHouSurService.getStaResult(samPoiHouSur.getId());
                        list.addAll(staResult);
                    }
                }
            }

            // 按结构类型分组
            Map<String, List<HouDamSta>> typeGroup = new HashMap<>();
            if (!PlatformObjectUtils.isEmpty(list)) {
                //List<String> types = new ArrayList<>();
                for (HouDamSta houDamSta : list) {
                    String type = houDamSta.getStructureType();
                    if (!typeGroup.containsKey(type)) {
                        typeGroup.put(type, new ArrayList<>());
                    }
                    typeGroup.get(type).add(houDamSta);
                }
                List<String> types = houseStructureManagementService.getPreStrType("预置");
                //获取房屋单体的总建筑面积之和
                //List<TotalFloorageVO> floorageList=houMonDataRepository.getTotalFloorageByXstmId(xstmId,supSamPoiIdList);
                //获取总建筑面积
                //HouseCategoryArea typeTotalArea = houseCategoryAreaRepository.getTypeTotalAreaByXstmId(xstmId,xsemCode);
                // 计算破坏比
                for (String type : types) {
                    Double destroy = 0.0;
                    Double serious = 0.0;
                    Double moderate = 0.0;
                    Double minor = 0.0;
                    Double intact = 0.0;
                    Double total = 0.0;
                    //Map<String, String> ratioMap = new HashMap<>();
                    List<HouDamSta> typeList = typeGroup.get(type);
                    if (!PlatformObjectUtils.isEmpty(typeList)) {
                        for (HouDamSta houDamSta : typeList) {
                            double destroyArea = Double.parseDouble(houDamSta.getDestroyArea());
                            double seriousDamageArea = Double.parseDouble(houDamSta.getSeriousDamageArea());
                            double moderateDamageArea = Double.parseDouble(houDamSta.getModerateDamageArea());
                            double minorDamageArea = Double.parseDouble(houDamSta.getMinorDamageArea());
                            double basicallyIntactArea = Double.parseDouble(houDamSta.getBasicallyIntactArea());
                            double totalArea = Double.parseDouble(houDamSta.getTotalArea());
                            destroy += destroyArea;
                            serious += seriousDamageArea;
                            moderate += moderateDamageArea;
                            minor += minorDamageArea;
                            intact += basicallyIntactArea;
                            total += totalArea;
                        }
                    }
                    /*if(floorageList.size()>0){
                        for(TotalFloorageVO item:floorageList){
                            if(type.equals(item.getStructureType())){
                                total = item.getFloorage().doubleValue();
                            }
                        }
                    }*/
                    /*if (XczhConstants.ONE_TYPE.equals(type)) {
                        total = typeTotalArea.getV1Area().doubleValue();
                    } else if (XczhConstants.TWO_TYPE.equals(type)) {
                        total = typeTotalArea.getV2Area().doubleValue();
                    } else if (XczhConstants.THREE_ONE_TYPE.equals(type)) {
                        total = typeTotalArea.getV3Area().doubleValue();
                    } else if (XczhConstants.THREE_TWO_TYPE.equals(type)) {
                        total = typeTotalArea.getV4Area().doubleValue();
                    } else if (XczhConstants.FOUR_TYPE.equals(type)) {
                        total = typeTotalArea.getV5Area().doubleValue();
                    } else if (XczhConstants.FIVE_ONE_TYPE.equals(type)) {
                        total = typeTotalArea.getV6Area().doubleValue();
                    } else if (XczhConstants.FIVE_TWO_TYPE.equals(type)) {
                        total = typeTotalArea.getV7Area().doubleValue();
                    } else if (XczhConstants.FIVE_THREE_TYPE.equals(type)) {
                        total = typeTotalArea.getV8Area().doubleValue();
                    } else if (XczhConstants.SIX_TYPE.equals(type)) {
                        total = typeTotalArea.getV9Area().doubleValue();
                    } else if (XczhConstants.SEVEN_TYPE.equals(type)) {
                        total = typeTotalArea.getV10Area().doubleValue();
                    }*/

                    HouseFailureRatioEntity houseFailureRatioEntity = new HouseFailureRatioEntity();
                    houseFailureRatioEntity.setId(UUIDGenerator.getUUID());
                    houseFailureRatioEntity.setXsemId(xsemId);
                    houseFailureRatioEntity.setXstmId(xstmId);
                    houseFailureRatioEntity.setEvaluationSubareaName(evaluationSubareaName);
                    houseFailureRatioEntity.setStructureType(type);
                    houseFailureRatioEntity.setIntactRatio(percentage(intact, total));
                    houseFailureRatioEntity.setMinorRatio(percentage(minor, total));
                    houseFailureRatioEntity.setModerateRatio(percentage(moderate, total));
                    houseFailureRatioEntity.setSeriousRatio(percentage(serious, total));
                    houseFailureRatioEntity.setDestroyRatio(percentage(destroy, total));
                    houseFailureRatioEntity.setDelFlag("0");
                    houseFailureRatioEntity.setCreateUser(PlatformSessionContext.getUserID());
                    houseFailureRatioEntity.setCreateTime(new Date());
                    //进行保存
                    houseEconomicLossAssessRepository.saveHouseFailureRatio(houseFailureRatioEntity);
                /*ratioMap.put("evaluationSubareaName", evaluationSubareaName);
                ratioMap.put("structureType", type);
                ratioMap.put("destroyRatio", percentage(destroy, total));
                ratioMap.put("seriousRatio", percentage(serious ,total));
                ratioMap.put("moderateRatio", percentage(moderate, total));
                ratioMap.put("minorRatio", percentage(minor, total));
                ratioMap.put("intactRatio", percentage(intact, total));
                result.add(ratioMap);*/
                }
                list.clear();
            }

        }
        //return result;
    }

    @Override
    public boolean save(HouseLossRatioEntity houseLossRatioEntity) {
        boolean res = false;
        String userID = PlatformSessionContext.getUserID();
//        HouseLossRatioEntity houseLossRatio = houseEconomicLossAssessRepository.getHouseLossRatio(houseLossRatioEntity.getXsemId());
//        if(PlatformObjectUtils.isEmpty(houseLossRatio)){
            //保存
            houseLossRatioEntity.setId(UUIDGenerator.getUUID());
            houseLossRatioEntity.setCreateTime(new Date());
            houseLossRatioEntity.setCreateUser(userID);
            houseLossRatioEntity.setDelFlag(YNEnum.N.toString());
            res = houseEconomicLossAssessRepository.save(houseLossRatioEntity);
//        }else{
//            //修改
//            houseLossRatioEntity.setUpdateTime(new Date());
//            houseLossRatioEntity.setUpdateUser(userID);
//            res = houseEconomicLossAssessRepository.update(houseLossRatioEntity);
//        }
        return res;
    }

    @Override
    public boolean updateHouseLossRatio(HouseLossRatioEntity houseLossRatioEntity) {
        //修改
        String userID = PlatformSessionContext.getUserID();
        houseLossRatioEntity.setUpdateTime(new Date());
        houseLossRatioEntity.setUpdateUser(userID);
        boolean res = houseEconomicLossAssessRepository.update(houseLossRatioEntity);
        return res;
    }

    @Override
    public HouseLossRatioEntity getHouseLossRatio(String xsemId) {
        return houseEconomicLossAssessRepository.getHouseLossRatio(xsemId);
    }

    private BigDecimal percentageConvert(BigDecimal percentage){
        return percentage.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
    }


    public static boolean isAllFieldsEmpty(Object obj) {
        return Arrays.stream(obj.getClass().getDeclaredFields())
                .allMatch(f -> {
                    f.setAccessible(true);
                    try {
                        return f.get(obj) == null || "".equals(f.get(obj).toString().trim());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                        return true;
                    }
                });
    }

    @Override
    public void getDirectEconomicLosses(String xsemId) {
        //获取当前地震事件
        EarEveManage earEveManage = earEveManageRepository.findById(xsemId);
        String xsemCode = earEveManage.getEventCode();
        List<HousesDirectEconomicLosses> list = new ArrayList<>();
        /*//根据评估子区id查询是否有已经计算的数据,有则返回数据,没有则再次计算
        list = houseEconomicLossAssessRepository.getHousesDirectEconomicLossesByXstmId(xstmId);
        if(!PlatformObjectUtils.isEmpty(list)){
            return list;
        }*/
        //删除上一次的计算结果
        houseEconomicLossAssessRepository.delHousesDirectEconomicLossesByXsemId(xsemId);
        //获取当前地震事件下数据齐全的所有的评估子区
        List<SurTaskManage> surTaskManageList = houseEconomicLossAssessService.getEvaluationSubArea(xsemId);
        for (SurTaskManage surTaskManage : surTaskManageList) {
            String xstmId = surTaskManage.getXstmId();
            String evaluationSubareaName = surTaskManage.getEvaluationSubareaName();


            /*//该评估子区同类房屋总建筑面积(单位为平方米) 和  该评估子区同类房屋某种破坏等级的破坏比
            Map<String, Map<String, BigDecimal>> result = getTotalBuildingArea(xstmId);*/
            //获取预置的十大结构类型
            List<String> types = houseStructureManagementService.getPreStrType("预置");
            //Sh——该评估子区同类房屋总建筑面积，单位为平方米；
            HouseCategoryArea typeTotalArea = houseCategoryAreaRepository.getTypeTotalAreaByXstmId(xstmId);
            if(isAllFieldsEmpty(typeTotalArea)){
                throw new RuntimeException("总建筑面积数据为空，请在【设定总建筑面积】模块中计算总建筑面积数据");
            }
            //Rh——该评估子区同类房屋某种破坏等级的破坏比；
            List<HouseFailureRatioEntity> houseFailureRatioList = houseEconomicLossAssessRepository.getHouseFailureRatioByXstmId(xstmId);
            if(CollectionUtils.isEmpty(houseFailureRatioList)){
                throw new RuntimeException("房屋破坏比数据为空，请在【房屋破坏比计算】模块中计算房屋破坏比数据");
            }
            //Dh——该评估子区同类房屋某种破坏等级的损失比；
            HouseLossRatioEntity houseLossRatio = houseEconomicLossAssessRepository.getHouseLossRatio(xsemId);
            if(PlatformObjectUtils.isEmpty(houseLossRatio)){
                throw new RuntimeException("房屋损失比数据为空，请在【房屋损失比计算】模块中计算房屋损失比数据");
            }
            //Ph——该评估子区同类房屋重置单价，单位为元每平方米。
            List<ResetPrice> resetPriceList = resetPriceRepository.getResetPriceByXsemId(xsemId);
            if(CollectionUtils.isEmpty(resetPriceList)){
                throw new RuntimeException("重置单价数据为空，请在【设定重置单价】模块中导入重置单价数据");
            }
            for(String type:types){
                //Sh 总面积
                Double totalArea = 0.0;
                //Rh 破坏比
                BigDecimal intactRatio = BigDecimal.ZERO; //基本完好
                BigDecimal minorRatio = BigDecimal.ZERO; //轻微破坏
                BigDecimal moderateRatio = BigDecimal.ZERO;//中等破坏
                BigDecimal seriousRatio = BigDecimal.ZERO; //严重破坏
                BigDecimal destroyRatio = BigDecimal.ZERO; //毁坏
                //Dh 损失比
                BigDecimal intact = BigDecimal.ZERO; //基本完好
                BigDecimal minor = BigDecimal.ZERO; //轻微破坏
                BigDecimal moderate = BigDecimal.ZERO;//中等破坏
                BigDecimal serious = BigDecimal.ZERO; //严重破坏
                BigDecimal destroy = BigDecimal.ZERO; //毁坏
                //ph 单价
                BigDecimal price = BigDecimal.ZERO;
                if (XczhConstants.ONE_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV1Area().doubleValue();
                } else if (XczhConstants.TWO_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV2Area().doubleValue();
                } else if (XczhConstants.THREE_ONE_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV3Area().doubleValue();
                } else if (XczhConstants.THREE_TWO_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV4Area().doubleValue();
                } else if (XczhConstants.FOUR_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV5Area().doubleValue();
                } else if (XczhConstants.FIVE_ONE_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV6Area().doubleValue();
                } else if (XczhConstants.FIVE_TWO_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV7Area().doubleValue();
                } else if (XczhConstants.FIVE_THREE_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV8Area().doubleValue();
                } else if (XczhConstants.SIX_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV9Area().doubleValue();
                } else if (XczhConstants.SEVEN_TYPE.equals(type)) {
                    totalArea = typeTotalArea.getV10Area().doubleValue();
                }

                if(XczhConstants.TWO_TYPE.equals(type) || XczhConstants.THREE_ONE_TYPE.equals(type) ||
                        XczhConstants.THREE_TWO_TYPE.equals(type) || XczhConstants.SEVEN_TYPE.equals(type)){//钢筋混凝土、砌体房屋     Dh
                    intact = percentageConvert(new BigDecimal(houseLossRatio.getIntact1()));
                    minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor1()));
                    moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate1()));
                    serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious1()));
                    destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy1()));
                }else if(XczhConstants.SIX_TYPE.equals(type)){//工业厂房
                    intact = percentageConvert (new BigDecimal(houseLossRatio.getIntact2()));
                    minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor2()));
                    moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate2()));
                    serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious2()));
                    destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy2()));
                }else if(XczhConstants.ONE_TYPE.equals(type)){//钢机构
                    intact = percentageConvert (new BigDecimal(houseLossRatio.getIntact4()));
                    minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor4()));
                    moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate4()));
                    serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious4()));
                    destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy4()));
                }else if(XczhConstants.FOUR_TYPE.equals(type) || XczhConstants.FIVE_ONE_TYPE.equals(type) ||
                        XczhConstants.FIVE_TWO_TYPE.equals(type)|| XczhConstants.FIVE_THREE_TYPE.equals(type)){//城镇平房、农村房屋
                    intact = percentageConvert (new BigDecimal(houseLossRatio.getIntact3()));
                    minor = percentageConvert (new BigDecimal(houseLossRatio.getMinor3()));
                    moderate = percentageConvert (new BigDecimal(houseLossRatio.getModerate3()));
                    serious = percentageConvert (new BigDecimal(houseLossRatio.getSerious3()));
                    destroy = percentageConvert (new BigDecimal(houseLossRatio.getDestroy3()));
                }

                for(ResetPrice resetPrice : resetPriceList){
                    if(type.equals(resetPrice.getStructureType())) {
                        price = new BigDecimal(resetPrice.getResetPrice());
                    }
                }
                for(HouseFailureRatioEntity houseFailureRatio : houseFailureRatioList){
                    if(type.equals(houseFailureRatio.getStructureType())) {
                        intactRatio = new BigDecimal(houseFailureRatio.getIntactRatio());
                        minorRatio = new BigDecimal(houseFailureRatio.getMinorRatio());
                        moderateRatio = new BigDecimal(houseFailureRatio.getModerateRatio());
                        seriousRatio = new BigDecimal(houseFailureRatio.getSeriousRatio());
                        destroyRatio = new BigDecimal(houseFailureRatio.getDestroyRatio());
                    }
                }
                //计算每一种破坏程度的值
                BigDecimal intactValue = calculation(BigDecimal.valueOf(totalArea), intactRatio, intact, price);
                BigDecimal minorValue = calculation(BigDecimal.valueOf(totalArea), minorRatio, minor, price);
                BigDecimal moderateValue = calculation(BigDecimal.valueOf(totalArea), moderateRatio, moderate, price);
                BigDecimal seriousValue = calculation(BigDecimal.valueOf(totalArea), seriousRatio, serious, price);
                BigDecimal destroyValue = calculation(BigDecimal.valueOf(totalArea), destroyRatio, destroy, price);
                //房屋损失(元)
                BigDecimal totalLoss = intactValue.add(minorValue).add(moderateValue).add(seriousValue).add(destroyValue);

                HousesDirectEconomicLosses housesDirectEconomicLosses = new HousesDirectEconomicLosses();
                housesDirectEconomicLosses.setId(UUIDGenerator.getUUID());
                housesDirectEconomicLosses.setXsemId(xsemId);
                housesDirectEconomicLosses.setXstmId(xstmId);
                housesDirectEconomicLosses.setEvaluationSubareaName(evaluationSubareaName);
                housesDirectEconomicLosses.setStructureType(type);
                housesDirectEconomicLosses.setIntactValue(intactValue.divide(new BigDecimal("10000")));//基本完好
                housesDirectEconomicLosses.setMinorValue(minorValue.divide(new BigDecimal("10000")));//轻微破坏
                housesDirectEconomicLosses.setModerateValue(moderateValue.divide(new BigDecimal("10000")));//中等破坏
                housesDirectEconomicLosses.setSeriousValue(seriousValue.divide(new BigDecimal("10000")));//严重破坏
                housesDirectEconomicLosses.setDestroyValue(destroyValue.divide(new BigDecimal("10000")));//毁坏
                housesDirectEconomicLosses.setTotalLoss(totalLoss.divide(new BigDecimal("10000")));//房屋损失(万元)
                housesDirectEconomicLosses.setCreateTime(new Date());
                housesDirectEconomicLosses.setCreateUser(PlatformSessionContext.getUserID());
                housesDirectEconomicLosses.setDelFlag(YNEnum.N.toString());
                list.add(housesDirectEconomicLosses);

            }

            /*for(HousesDirectEconomicLosses housesDirectEconomicLosses : list){
                houseEconomicLossAssessRepository.saveHousesDirectEconomicLosses(housesDirectEconomicLosses);
            }*/
            houseEconomicLossAssessRepository.batchSave(list);
            list.clear();
        }




        /*//Lh=Sh×Rh×Dh×Ph
        for(String key: result.keySet()){
            Map<String, BigDecimal> map = result.get(key);
            BigDecimal totalArea = map.get("totalArea");//总面积   Sh
            for(ResetPrice resetPrice : resetPriceList){
                if(key.equals(resetPrice.getStructureType())){
                    BigDecimal price = new BigDecimal(resetPrice.getResetPrice()); //单价   Ph
                    BigDecimal intactRatio = map.get("intactRatio");//基本完好      Rh
                    BigDecimal minorRatio = map.get("minorRatio");//轻微破坏
                    BigDecimal moderateRatio = map.get("moderateRatio");//中等破坏
                    BigDecimal seriousRatio = map.get("seriousRatio");//严重破坏
                    BigDecimal destroyRatio = map.get("destroyRatio");//毁坏

                    BigDecimal intact = BigDecimal.ZERO; //基本完好
                    BigDecimal minor = BigDecimal.ZERO; //轻微破坏
                    BigDecimal moderate = BigDecimal.ZERO;//中等破坏
                    BigDecimal serious = BigDecimal.ZERO; //严重破坏
                    BigDecimal destroy = BigDecimal.ZERO; //毁坏
                    if(key.equals("1")||key.equals("2")||key.equals("3")||key.equals("9")){//钢筋混凝土、砌体房屋     Dh
                        intact = new BigDecimal(houseLossRatio.getIntact1());//基本完好
                        minor = new BigDecimal(houseLossRatio.getMinor1());//轻微破坏
                        moderate = new BigDecimal(houseLossRatio.getModerate1());//中等破坏
                        serious = new BigDecimal(houseLossRatio.getSerious1());//严重破坏
                        destroy = new BigDecimal(houseLossRatio.getDestroy1());//毁坏
                    }else if(key.equals("8")){//工业厂房
                        intact = new BigDecimal(houseLossRatio.getIntact2());//基本完好
                        minor = new BigDecimal(houseLossRatio.getMinor2());//轻微破坏
                        moderate = new BigDecimal(houseLossRatio.getModerate2());//中等破坏
                        serious = new BigDecimal(houseLossRatio.getSerious2());//严重破坏
                        destroy = new BigDecimal(houseLossRatio.getDestroy2());//毁坏
                    }else if(key.equals("0")){//钢机构
                        intact = new BigDecimal(houseLossRatio.getIntact4());//基本完好
                        minor = new BigDecimal(houseLossRatio.getMinor4());//轻微破坏
                        moderate = new BigDecimal(houseLossRatio.getModerate4());//中等破坏
                        serious = new BigDecimal(houseLossRatio.getSerious4());//严重破坏
                        destroy = new BigDecimal(houseLossRatio.getDestroy4());//毁坏
                    }else if(key.equals("4")||key.equals("5")||key.equals("6")||key.equals("7")){//城镇平房、农村房屋
                        intact = new BigDecimal(houseLossRatio.getIntact3());//基本完好
                        minor = new BigDecimal(houseLossRatio.getMinor3());//轻微破坏
                        moderate = new BigDecimal(houseLossRatio.getModerate3());//中等破坏
                        serious = new BigDecimal(houseLossRatio.getSerious3());//严重破坏
                        destroy = new BigDecimal(houseLossRatio.getDestroy3());//毁坏
                    }
                    //计算每一种破坏程度的值
                    BigDecimal intactValue = calculation(totalArea, intactRatio, intact, price);
                    BigDecimal minorValue = calculation(totalArea, minorRatio, minor, price);
                    BigDecimal moderateValue = calculation(totalArea, moderateRatio, moderate, price);
                    BigDecimal seriousValue = calculation(totalArea, seriousRatio, serious, price);
                    BigDecimal destroyValue = calculation(totalArea, destroyRatio, destroy, price);
                    //房屋损失(元)
                    BigDecimal totalLoss = intactValue.add(minorValue).add(moderateValue).add(seriousValue).add(destroyValue);

                    HousesDirectEconomicLosses housesDirectEconomicLosses = new HousesDirectEconomicLosses();
                    housesDirectEconomicLosses.setId(UUIDGenerator.getUUID());
                    housesDirectEconomicLosses.setXsemId(xsemId);
                    housesDirectEconomicLosses.setXstmId(xstmId);
                    housesDirectEconomicLosses.setEvaluationSubareaName(evaluationSubareaName);
                    housesDirectEconomicLosses.setStructureType(key);
                    housesDirectEconomicLosses.setIntactValue(intactValue);//基本完好
                    housesDirectEconomicLosses.setMinorValue(minorValue);//轻微破坏
                    housesDirectEconomicLosses.setModerateValue(moderateValue);//中等破坏
                    housesDirectEconomicLosses.setSeriousValue(seriousValue);//严重破坏
                    housesDirectEconomicLosses.setDestroyValue(destroyValue);//毁坏
                    housesDirectEconomicLosses.setTotalLoss(totalLoss);//房屋损失(元)
                    housesDirectEconomicLosses.setCreateTime(new Date());
                    housesDirectEconomicLosses.setCreateUser(userID);
                    housesDirectEconomicLosses.setDelFlag(YNEnum.N.toString());
                    list.add(housesDirectEconomicLosses);
                }
            }
        }
        for(HousesDirectEconomicLosses housesDirectEconomicLosses : list){
            houseEconomicLossAssessRepository.saveHousesDirectEconomicLosses(housesDirectEconomicLosses);
        }
        return list;*/
    }

    @Override
    public List<DisasterAreasHousesDirectEconomicLosses> getDisasterAreasHousesDirectEconomicLosses(String xsemId) {
        //获取当前地震事件下数据齐全的评估子区
        List<SurTaskManage> SurTaskManageList = getEvaluationSubArea(xsemId);
        List<DisasterAreasHousesDirectEconomicLosses> list = new ArrayList<>();
        //double mergeValues = 0.0;//所有评估子区合并值
        BigDecimal mergeValues = BigDecimal.ZERO;
        houseEconomicLossAssessRepository.deleteDisasterAreasHousesDirectEconomicLosses(xsemId);
        for(SurTaskManage surTaskManage : SurTaskManageList){
            String xstmId = surTaskManage.getXstmId();
            String sumTotal = houseEconomicLossAssessRepository.getSumTotal(xstmId);//根据评估子区id获取评估子区各类房屋不同破坏状态下的房屋直接经济损失
            //DisasterAreasHousesDirectEconomicLosses  disasterAreas = houseEconomicLossAssessRepository.getDisasterAreasHousesByXstmId(xstmId);
            if(!PlatformObjectUtils.isEmpty(sumTotal)) {
                DisasterAreasHousesDirectEconomicLosses disasterAreasHouses = new DisasterAreasHousesDirectEconomicLosses();
                disasterAreasHouses.setId(UUIDGenerator.getUUID());
                disasterAreasHouses.setXsemId(xsemId);
                disasterAreasHouses.setXstmId(xstmId);
                disasterAreasHouses.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                disasterAreasHouses.setHousesLosses(new BigDecimal(sumTotal));
                disasterAreasHouses.setCreateTime(new Date());
                disasterAreasHouses.setCreateUser(PlatformSessionContext.getUserID());
                disasterAreasHouses.setDelFlag(YNEnum.N.toString());
                list.add(disasterAreasHouses);
                houseEconomicLossAssessRepository.saveDisasterAreasHousesDirectEconomicLosses(disasterAreasHouses);
            }else{
                DisasterAreasHousesDirectEconomicLosses disasterAreasHouses = new DisasterAreasHousesDirectEconomicLosses();
                disasterAreasHouses.setEvaluationSubareaName(surTaskManage.getEvaluationSubareaName());
                list.add(disasterAreasHouses);
            }
        }

        List<DisasterAreasHousesDirectEconomicLosses> valueList = houseEconomicLossAssessRepository.getDisasterAreasHousesDirectEconomicLossesByXsemId(xsemId);
        for (DisasterAreasHousesDirectEconomicLosses entity : valueList) {
            BigDecimal housesLosses = entity.getHousesLosses();
            mergeValues=mergeValues.add(housesLosses);
        }
        DisasterAreasHousesDirectEconomicLosses entity = new DisasterAreasHousesDirectEconomicLosses();
        entity.setEvaluationSubareaName("灾区");
        entity.setHousesLosses(mergeValues);
        list.add(entity);
        return list;
    }

    @Override
    public List<DisasterAreasHousesDirectEconomicLosses> getDisasterAreasHousesData(String xsemId) {
        List<DisasterAreasHousesDirectEconomicLosses> list = houseEconomicLossAssessRepository.getDisasterAreasHousesDirectEconomicLossesByXsemId(xsemId);
        //double mergeValues = 0.0;//所有评估子区合并值
        BigDecimal mergeValues = BigDecimal.ZERO;//所有评估子区合并值
        for (DisasterAreasHousesDirectEconomicLosses entity : list) {
            mergeValues.add(entity.getHousesLosses());
        }
        DisasterAreasHousesDirectEconomicLosses entity = new DisasterAreasHousesDirectEconomicLosses();
        entity.setEvaluationSubareaName("灾区");
        entity.setHousesLosses(mergeValues);
        list.add(entity);
        return list;
    }

    /*private BigDecimal calculation(double Sh,double Rh,double Dh,double Ph){
        double res = Sh*Rh*Dh*Ph;
        BigDecimal result = BigDecimal.valueOf(res); // 将浮点数转换为BigDecimal
        return result.setScale(2, BigDecimal.ROUND_HALF_UP);
    }*/
    private BigDecimal calculation(BigDecimal Sh,BigDecimal Rh,BigDecimal Dh,BigDecimal Ph){
        BigDecimal result = Sh.multiply(Rh).multiply(Dh).multiply(Ph);
        return result.setScale(2, RoundingMode.HALF_UP);
    }


    //该评估子区同类房屋总建筑面积(单位为平方米) 和  该评估子区同类房屋某种破坏等级的破坏比
    private Map<String, Map<String, BigDecimal>> getTotalBuildingArea(String xstmId){
        List<HouDamSta> list  = new ArrayList<>();
        //通过评估子区id获取到抽样点
        List<SamPoiData> samPoiList = samPoiDataService.getSamPoiListByXstmId(xstmId);
        for(SamPoiData samPoiData : samPoiList){
            //通过抽样点获取到房屋抽样点
            SamPoiHouSur samPoiHouSur = samPoiHouSurService.getTaskListByXspdId(samPoiData.getId());
            //通过房屋抽样点id获取到不同结构不同破坏状态下的面积和百分比
            if (!PlatformObjectUtils.isEmpty(samPoiHouSur) && !PlatformObjectUtils.isEmpty(samPoiHouSur.getId())) {
                List<HouDamSta> staResult = samPoiHouSurService.getStaResult(samPoiHouSur.getId());
                list.addAll(staResult);
            }
        }
        Map<String, Map<String, BigDecimal>> result = new HashMap<>();
        // 按结构类型分组
        Map<String, List<HouDamSta>> typeGroup = new HashMap<>();
        if (!PlatformObjectUtils.isEmpty(list)) {
            for (HouDamSta houDamSta : list) {
                String type = houDamSta.getStructureType();
                if (!typeGroup.containsKey(type)) {
                    typeGroup.put(type, new ArrayList<>());
                }
                typeGroup.get(type).add(houDamSta);
            }
            //同种类型的总面积
            for (String type : typeGroup.keySet()) {
                BigDecimal destroy=BigDecimal.ZERO;
                BigDecimal serious=BigDecimal.ZERO;
                BigDecimal moderate=BigDecimal.ZERO;
                BigDecimal minor=BigDecimal.ZERO;
                BigDecimal intact=BigDecimal.ZERO;
                BigDecimal total=BigDecimal.ZERO;
                Map<String, BigDecimal> ratioMap = new HashMap<>();
                List<HouDamSta> typeList = typeGroup.get(type);
                for (HouDamSta houDamSta : typeList) {
                    BigDecimal destroyArea = new BigDecimal(houDamSta.getDestroyArea());
                    BigDecimal seriousDamageArea =  new BigDecimal(houDamSta.getSeriousDamageArea());
                    BigDecimal moderateDamageArea =  new BigDecimal(houDamSta.getModerateDamageArea());
                    BigDecimal minorDamageArea =  new BigDecimal(houDamSta.getMinorDamageArea());
                    BigDecimal basicallyIntactArea =  new BigDecimal(houDamSta.getBasicallyIntactArea());
                    destroy=destroy.add(destroyArea);
                    serious=serious.add(seriousDamageArea);
                    moderate=moderate.add(moderateDamageArea);
                    minor=minor.add(minorDamageArea);
                    intact=intact.add(basicallyIntactArea);
                    BigDecimal totalArea = new BigDecimal(houDamSta.getTotalArea());
                    total=total.add(totalArea);
                }
                ratioMap.put("destroyRatio", halfAdjust(destroy, total));//毁坏
                ratioMap.put("seriousRatio", halfAdjust(serious ,total));//严重破坏
                ratioMap.put("moderateRatio", halfAdjust(moderate, total));//中等破坏
                ratioMap.put("minorRatio", halfAdjust(minor, total));//轻微破坏
                ratioMap.put("intactRatio", halfAdjust(intact, total));//基本完好
                ratioMap.put("totalArea", total);//总面积
                result.put(type,ratioMap);
            }
        }
        return result;
    }

    private BigDecimal halfAdjust(BigDecimal a,BigDecimal b){
        BigDecimal result = a.divide(b, 2, BigDecimal.ROUND_HALF_UP);
        return result;
    }

    //四舍五入
    private String percentage(Double a,Double b){
        if(a ==0 || b==0 || a ==0.0 || b==0.0){
            return "0.00";
        }
        double rateStr = (new BigDecimal(a / b).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue()) * 100;
        DecimalFormat decimalFormat = new DecimalFormat("0.00#");
        //String format = String.format("%.2f", rateStr);
        //return format+"%";
        return decimalFormat.format(rateStr);
    }

}
